package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.domain.OrderDetail;
import com.itheima.domain.Orders;
import com.itheima.domain.User;
import com.itheima.dto.OrdersDto;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/order")
@Api(tags = "订单相关接口")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;

    /**
     * 订单信息分页查询
     *
     * @return
     */
    @ApiOperation(value = "订单分页查询")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "page", value = "页码", readOnly = true),
                    @ApiImplicitParam(name = "pageSize", value = "当前页条目数", readOnly = true),
            }
    )
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page, Integer pageSize, HttpServletRequest request) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //获取当前登录用户信息
        Long userId = (Long) request.getSession().getAttribute("user");
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersPages = ordersService.page(ordersPage, queryWrapper);
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<Orders> records = ordersPages.getRecords();
        log.info("基本订单信息:{}", records.toString());
        List<OrdersDto> collect = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            log.info("订单详情：---------------------------------{}", item);
            BeanUtils.copyProperties(item, ordersDto);
            //根据订单获取订单明细表
            LambdaQueryWrapper<OrderDetail> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.eq(item.getId() != null, OrderDetail::getOrderId, item.getId());
            List<OrderDetail> list = orderDetailService.list(ordersLambdaQueryWrapper);
            ordersDto.setOrderDetails(list);
//            //获取名字
//            Long id = item.getUserId();
//            ordersDto.setUserId(id);
//            //获取电话
//            String phone = item.getPhone();
//            ordersDto.setPhone(phone);
//            //获取地址
//            String address = item.getAddress();
//            ordersDto.setAddress(address);
//            //获取收货人信息
//            String consignee = item.getConsignee();
//            ordersDto.setConsignee(consignee);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(collect);
        return R.success(ordersDtoPage);
    }

    /**
     * 查询所有订单信息
     *
     * @return
     */
    @ApiOperation(value = "订单信息查询")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "page", value = "页码", readOnly = true),
                    @ApiImplicitParam(name = "pageSize", value = "当前页条目数", readOnly = true),
                    @ApiImplicitParam(name = "number", value = "订单id", readOnly = true),
                    @ApiImplicitParam(name = "beginTime", value = "起始时间", readOnly = true),
                    @ApiImplicitParam(name = "endTime", value = "结束时间", readOnly = true)
            }
    )
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, Long number, String beginTime, String endTime, HttpServletRequest request) {
        //存分页订单信息
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //存分页订单信息及订单明细
        Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //按照订单号查询
        queryWrapper.eq(number != null, Orders::getNumber, number);
        //小于结束时间
        queryWrapper.le(endTime != null, Orders::getOrderTime, endTime);
        //大于起始时间
        queryWrapper.ge(beginTime != null, Orders::getOrderTime, beginTime);
        //分页查询信息
        queryWrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> orderDetailPage = ordersService.page(ordersPage, queryWrapper);
        //查询出的订单集合
        List<Orders> records = orderDetailPage.getRecords();
        BeanUtils.copyProperties(orderDetailPage, ordersDtoPage, "records");
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            //获取点单用户并存入dto
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long userId = item.getUserId();
            User user = userService.getById(userId);
            log.info("用户信息:{}", user);
            ordersDto.setUserName(user.getName());
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoList);
        log.info("订单信息:{}", ordersDtoPage.getRecords().toString());
        //返回订单信息
        return R.success(ordersDtoPage);
    }

    /**
     * 提交订单信息
     *
     * @param orders
     * @param request
     * @return
     */
    @ApiOperation(value = "提交订单信息")



    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpServletRequest request) {
        //获取当前登录用户信息
        Long user = (Long) request.getSession().getAttribute("user");
        Long currentId = BaseContext.getCurrentId();
        //保存订单基本信息
        log.info("订单数据：{}", orders);
        ordersService.submit(orders);
        return R.success("下单成功");

    }

    /**
     * 订单状态信息修改
     *
     * @param orders
     * @return
     */
    @ApiOperation(value = "订单信息修改")



    @PutMapping
    public R<Orders> update(@RequestBody Orders orders) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(orders != null, Orders::getId, orders.getId());

        ordersService.update(orders, queryWrapper);

        return R.success(orders);
    }

    /**
     * 再来一单
     *
     * @return
     */
    @ApiOperation(value = "再次点单")



    @PostMapping("/again")
    public R<Orders> again(@RequestBody Orders orders) {
        Long id = orders.getId();
        Orders byId = ordersService.getById(id);
        return R.success(byId);
    }

}
